package redis

import (
	"github.com/go-redis/redis"
	"github.com/satori/go.uuid"
	"strconv"
	"time"
)

func NewPost(pid string, communityID string) error {

	pipeline := client.TxPipeline()
	// 帖子时间
	pipeline.ZAdd(KeyPostTimeZSet, redis.Z{
		Score:  float64(time.Now().Unix()),
		Member: pid,
	})

	// 帖子分数
	pipeline.ZAdd(KeyPostScoreZSet, redis.Z{
		Score:  float64(time.Now().Unix()),
		Member: pid,
	})
	// 更新：把帖子id加到社区的set
	cKey := KeyCommunitySetPX + communityID
	pipeline.SAdd(cKey, pid)
	_, err := pipeline.Exec()
	return err
}

func ListPostID(cid uint64, offset uint64, limit uint64) (ids []uint64, err error) {

	var result []string
	if cid == 0 {
		result, err = client.ZRange(KeyPostScoreZSet, int64(offset), int64(offset+limit)).Result()
	} else {
		// ZINTERSTORE
		key := uuid.NewV4().String()

		pipeline := client.TxPipeline()
		_, err = pipeline.ZInterStore(key, redis.ZStore{
			Aggregate: "MAX",
		}, KeyPostScoreZSet, KeyCommunitySetPX+strconv.FormatUint(cid, 10)).Result()

		if err != nil {
			return
		}

		pipeline.Expire(key, 30*time.Second)

		_, err = pipeline.Exec()
		if err != nil {
			return
		}

		result, err = client.ZRange(key, int64(offset), int64(offset+limit)).Result()
	}

	if err != nil {
		return
	}

	ids = make([]uint64, 0, limit)
	for _, v := range result {
		id, _ := strconv.ParseUint(v, 10, 64)
		ids = append(ids, id)
	}
	return
}
